package com.pn.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/*
  处理服务调用传递token的拦截器:
  1)实现RequestInterceptor接口并重写apply()
  2)将RequestInterceptor实现类的bean对象加入IOC容器 --- 拦截器
 */
@Component
public class TokenInterceptor implements RequestInterceptor {

    //拦截器拦截到请求执行的内容:
    @Override
    public void apply(RequestTemplate requestTemplate) {

        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        /*
          ServletRequestAttributes不为null,且拿到的请求头Authorization的值即token不为null也不为空串,
          说明是客户端请求:
          将token从请求头Authorization中拿出来,再重新放入发出服务调用请求的RequestTemplate对象的请求头
          Authorization中
         */
        if(requestAttributes!=null){
            HttpServletRequest request = requestAttributes.getRequest();
            String token = request.getHeader("Authorization");
            if(StringUtils.hasText(token)){
                requestTemplate.header("Authorization", token);
                return;
            }
        }

        /*
          ServletRequestAttributes为null,或者拿到的请求头Authorization的值即token为null或为空串,
          说明是是服务调用的请求或者是第三方信任的服务的调用请求:
          生成一个永不过期的token,并将token放入发出服务调用请求的RequestTemplate对象的请求头Authorization中
         */
        requestTemplate.header("Authorization", "bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJhbGwiXSwiZXhwIjozODMzNDk5NjcyLCJqdGkiOiJmYzU1YzhlMS1hYTM0LTQ2ZDItOTQ0ZC1mMmI3ZjdhMmU3YzQiLCJjbGllbnRfaWQiOiJzZXJ2aWNlIn0.Q0RAaJ3w3sImDYtoX-w1U9cpvM7oHI8BU9vBvv1aNqGsrYXvWFRDL1J8UT-pW8cVEmfmUndXGKqD7JxXk7iEBh24tblnmAZIYGS6niPh9OksADFcQnwRH88OABun79_mZkgoV3ypiH3ryHLnnBB0PobbJWL6rbkYS0tKJ6vNG-VidYmevH_OceujSVPJvalfHAcM9vxOR8TT9WfcuCDSRQChBn5z6KvanJnuNkEDqeOBYd61a6Y5khGshbV7a5GM7xkPMl9QnzcO6VrH6Do308IlnGm35fjiDL2tGFEZIIu8yKTPcIE54lEL03bS-1A43_e7BRk-uBl9m49Dlq2bMw");
    }
}
